#include "yzjwriter.h"
#include "servermonitor.h"

#include <QList>

YzjWriter::YzjWriter()
{
    ServerMonitor oMonitor;
    item = oMonitor.CollectPartsTogether();

    /*
        keyValue.first = "user";
        keyValue.second = "12.3";
        item.insert("CPU",keyValue);
        //
        keyValue.first = "nice";
        keyValue.second = "12.3";
        item.insert("CPU",keyValue);
        //
        keyValue.first = "idle";
        keyValue.second = "13.5";
        item.insert("CPU",keyValue);
        //
        keyValue.first = "speed";
        keyValue.second = "4589";
        item.insert("Disk",keyValue);
        //
        keyValue.first = "total";
        keyValue.second = "23456";
        item.insert("Memory",keyValue);
        //
        keyValue.first = "free";
        keyValue.second = "1234";
        item.insert("Memory",keyValue);
        */
}

void YzjWriter::WriteItem(QStringPairMap itemPair){
        xml.writeStartElement("Item");
        xml.writeAttribute("Value", itemPair.second);
        xml.writeTextElement("Key", itemPair.first);
        xml.writeEndElement();
}

void YzjWriter::WriteCategory(QString cate, QMultiMap<QString, QStringPairMap> item){
        xml.writeStartElement("Category");
        xml.writeAttribute("folded", "yes" );
        xml.writeTextElement("Title", cate);
        //child
        foreach(QStringPairMap kv, item.values(cate))
                WriteItem(kv);
        xml.writeEndElement();
}

void YzjWriter::WriteRecord(QMultiMap<QString,QStringPairMap> item){
    static int countRecord = 0;
    QString key;
    QList<QString> keys = item.keys();
    // 删除QList中重复项
    for(int i = 0; i < keys.count()-1;){
        if(keys[i] == keys[i+1])
            keys.removeAt(i);
        else
                i++;
    }
    xml.writeStartElement("Record");
    xml.writeAttribute("count",QString::number(++countRecord));
    for(int j = 0; j < keys.count(); j++){
        key = keys[j];
            WriteCategory(key,item);
    }

    xml.writeEndElement();
}

bool YzjWriter::WriteYzj(QIODevice *device){
        xml.setDevice(device);
        xml.setAutoFormatting(true);
        xml.writeStartDocument();
        xml.writeDTD("<!DOCTYPE yzj>");

        xml.writeStartElement("yzj");
        xml.writeAttribute("version", "1.0");

        // 这个地方有大文章，有一个线程经过2s中启动WriteRecord函数
        // 依然没有解决 0213
//        for(int a = 0; a < 100; a++)
        WriteRecord(item);

        xml.writeEndElement();
        xml.writeEndDocument();
        return true;
}
